package com.xinyan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinyan.config.RedisKeyConstant;
import com.xinyan.pojo.SprayAdItem;
import com.xinyan.mapper.SprayAdItemMapper;
import com.xinyan.service.ISprayAdItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xzlf
 * @since 2024-03-19 17:57:43
 */
@Service
public class SprayAdItemServiceImpl implements ISprayAdItemService {

    @Autowired
    private SprayAdItemMapper sprayAdItemMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<SprayAdItem> findAdItemList() {
        List<SprayAdItem> adItemList = (List<SprayAdItem>) redisTemplate.opsForValue().get(RedisKeyConstant.ADITEM);
        if (CollectionUtils.isEmpty(adItemList)) {
            adItemList = updateRedisAditem();
        }
        return adItemList;
    }


    @Override
    public void addAdItem(SprayAdItem sprayAdItem) {
        sprayAdItem.setStatus(1);
        sprayAdItemMapper.insert(sprayAdItem);

        updateRedisAditem();
    }

    @Override
    public void deleteAdItem(int id) {
        SprayAdItem sprayAdItem = sprayAdItemMapper.selectById(id);
        sprayAdItem.setStatus(3);
        sprayAdItemMapper.updateById(sprayAdItem);

    }

    private List<SprayAdItem> updateRedisAditem() {
        List<SprayAdItem> adItemList = sprayAdItemMapper.selectList(new LambdaQueryWrapper<SprayAdItem>()
                .eq(SprayAdItem::getStatus, 1)
                .orderByDesc(SprayAdItem::getUpdateTime)
                .last("limit 4")
        );

        redisTemplate.opsForValue().set(RedisKeyConstant.ADITEM, adItemList);
        redisTemplate.expire(RedisKeyConstant.ADITEM, RedisKeyConstant.ADITME_TIMEOUT, TimeUnit.HOURS);
        return adItemList;
    }
}
